/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.scene.controller;

import com.alibaba.fastjson.JSONObject;
import com.koron.common.Excel;
import com.koron.common.StaffAttribute;
import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.permission.SPIAccountAnno;
import com.koron.common.web.Util;
import com.koron.hiddendanger.domain.HiddenDangerDiscovery;
import com.koron.hiddendanger.domain.ItemCheckRecord;
import com.koron.scene.domain.Device;
import com.koron.scene.domain.DeviceCheck;
import com.koron.scene.domain.DeviceCheckRelation;
import com.koron.scene.domain.DeviceHiddenDanger;
import com.koron.scene.service.api.DeviceCheckService;
import com.koron.scene.utils.BusinessCode;
import com.koron.system.annotation.Log;
import com.koron.system.discrete.BusinessManipulation;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;
import org.swan.bean.MessageBean;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.InputStream;
import java.util.*;

@Api(tags = "deviceCheck", description = "设备检查接口")
@RestController
@RequestMapping("/deviceCheck")
public class DeviceCheckController {

    private final static  Logger logger = LoggerFactory.getLogger(DeviceCheckController.class);

    @Autowired
    private DeviceCheckService deviceCheckService;

    @Autowired
    private Util util;

    private void setProperties(DeviceCheck source, StaffBean user) {
        source.setAddUser(user.getCode());
        source.setAddUserName(user.getName());
        source.setAddTime(new Date());
        source.setUpdateUserName(user.getName());
        source.setUpdateTime(source.getAddTime());
        source.setUpdateUser(user.getCode());
    }


    @ApiOperation("存储设备检查记录")
    @RequestMapping(value = "/save.htm", method = {RequestMethod.POST})
    @Log(title = "新增、修改设备检查记录", businessModule = "设备检查", businessManipulation = BusinessManipulation.INSERT)
    public MessageBean<String> save(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestBody DeviceCheck deviceCheck) {
        if (user == null) {
            return MessageBean.create(BusinessCode.NO_LOGIN.getCode(), BusinessCode.NO_LOGIN.getDescription(), String.class);
        }
        if (deviceCheck == null) {
            return MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), String.class);
        }
        if (StringUtils.isBlank(deviceCheck.getTitle()) || StringUtils.isBlank(deviceCheck.getCheckEmployeeCode()) || StringUtils.isBlank(deviceCheck.getCheckEmployeeName())
                || StringUtils.isBlank(deviceCheck.getExecuterCode()) || StringUtils.isBlank(deviceCheck.getExecuterName())) {
            return MessageBean.create(BusinessCode.INSUFFICIENT_PARAM.getCode(), BusinessCode.INSUFFICIENT_PARAM.getDescription(), String.class);
        }
        setProperties(deviceCheck, user);
        Integer result = deviceCheckService.persist(deviceCheck);
        BusinessCode bc = BusinessCode.valueOf(result);
        MessageBean<String> msg = MessageBean.create(bc.getCode(), bc.getDescription(), String.class);
        if (result.intValue() == BusinessCode.SUCCESS.getCode()) {
            msg.setData(deviceCheck.getId());
        }
        return msg;
    }


    @ApiOperation("批量删除设备检查记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "检查记录Id,多个之间用逗号分开", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/batchDelete.htm", method = RequestMethod.POST)
    @Log(title = "批量删除设备检查记录", businessManipulation = BusinessManipulation.DELETE)
    public MessageBean<Boolean> batchDelete(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, String ids) {
        MessageBean<Boolean> msg = new MessageBean<>();
        if (user == null) {
            msg.setCode(BusinessCode.NO_LOGIN.getCode());
            msg.setDescription(BusinessCode.NO_LOGIN.getDescription());
            return msg;
        }
        if (StringUtils.isEmpty(ids)) {
            return MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Boolean.class);
        }
        try {
            String[] idArray = ids.split("[,，]");
            for (String id : idArray) {
                DeviceCheck deviceCheck = deviceCheckService.fetchOne(id);
                if (deviceCheck.getStatus() != 1) {
                    return MessageBean.create(BusinessCode.CHECK_CANNOT_REMOVE.getCode(), BusinessCode.CHECK_CANNOT_REMOVE.getDescription(), Boolean.class);
                }
            }
            msg.setData(deviceCheckService.batchDetele(Arrays.asList(idArray)));
            msg.setDescription(BusinessCode.SUCCESS.getDescription());
            msg.setCode(BusinessCode.SUCCESS.getCode());
            return msg;
        } catch (Exception e) {
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }


    @ApiOperation("查询设备检查记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode", value = "公司code" , paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "title", value = "标题" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "checkEmployeeName", value = "检查负责人姓名" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "executerName", value = "检查人姓名" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "状态, 1草稿2提交" , dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "keyword", value = "关键词" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "当前页", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/list.htm", method = RequestMethod.POST)
    public MessageBean<DataBean<DeviceCheck>> list(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(required = false) String corpCode, @RequestParam(required = false) String title, @RequestParam(required = false) String checkEmployeeName,
                                                   @RequestParam(required = false) String executerName, @RequestParam(required = false) Integer status, @RequestParam(required = false) String keyword,
                                                   @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "15") Integer pageSize) {
        MessageBean<DataBean<DeviceCheck>> msg = new MessageBean<>();
        if (user == null) {
            msg.setCode(BusinessCode.NO_LOGIN.getCode());
            msg.setDescription(BusinessCode.NO_LOGIN.getDescription());
            return msg;
        }
        Integer start = (page <= 1) ? 0 : (page - 1) * pageSize;
        try {
            DataBean<DeviceCheck> dataBean = deviceCheckService.fetchDeviceChecks(corpCode, title, checkEmployeeName, executerName, status, start, pageSize, keyword);
            msg.setData(dataBean);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription(BusinessCode.SUCCESS.getDescription());
        } catch (Exception e) {
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }


    @ApiOperation("设备检查记录详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "设备检查记录Id", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/detail.htm", method = RequestMethod.POST)
    public MessageBean<DeviceCheck> detail(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(required = true) final String id) {
        MessageBean<DeviceCheck> msg = new MessageBean<>();
        if (user == null) {
            msg.setCode(BusinessCode.NO_LOGIN.getCode());
            msg.setDescription(BusinessCode.NO_LOGIN.getDescription());
            return msg;
        }
        if (StringUtils.isEmpty(id)) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
            return msg;
        }
        try {
            msg.setData(deviceCheckService.fetchOne(id));
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription(BusinessCode.SUCCESS.getDescription());
        } catch (Exception e) {
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }


    @ApiOperation("存储设备检查结果明细")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userCode", value = "当前登录人code,pc端不传，app必传" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "deviceCheckRecordId", value = "设备检查记录Id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "deviceId", value = "设备Id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "checkListEntryId", value = "检查表记录Id" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "items", value = "检查表检查项json格式" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "normal", value = "是否正常" , dataType = "boolean", paramType = "query"),
            @ApiImplicitParam(name = "hiddenDangers", value = "隐患列表json格式" , dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/saveCheckResult.htm", method = RequestMethod.POST)
    @Log(title = "新增、修改设备检查结果明细", businessManipulation = BusinessManipulation.INSERT)
    public MessageBean<Boolean> saveCheckResult(HttpServletRequest request, @SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(required = false) String userCode,
                                                @RequestParam String deviceCheckRecordId, @RequestParam String deviceId, @RequestParam(required = false) String checkListEntryId, @RequestParam(required = false) String items, @RequestParam(required = false) boolean normal,
                                                @RequestParam(required = false) String hiddenDangers) {
        MessageBean<Boolean> msg = new MessageBean<>();
        if (null == user) {
            List<StaffBean> staffBeanList = (List<StaffBean>) util.staff(userCode, null).getData();
            if (null != staffBeanList && staffBeanList.size() > 0)
                user = staffBeanList.get(0);
        }
        if (null == user) {
            msg.setCode(BusinessCode.NO_LOGIN.getCode());
            msg.setDescription(BusinessCode.NO_LOGIN.getDescription());
            return msg;
        }
        DeviceCheckRelation relation = new DeviceCheckRelation();
        relation.setDeviceCheckRecordId(deviceCheckRecordId);
        relation.setDeviceId(deviceId);
        relation.setNormal(normal);
        // 如果选择了检查表相关信息，获取数据
        if (StringUtils.isNotEmpty(checkListEntryId)) {
            relation.setCheckListEntryId(checkListEntryId);
            if (StringUtils.isEmpty(items)) {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("检查表详情不能为空");
                return msg;
            }
            List<ItemCheckRecord> itemList = JSONObject.parseArray(items, ItemCheckRecord.class);
            relation.setItemList(itemList);
        }
        List<DeviceHiddenDanger> deviceHiddenDangers = JSONObject.parseArray(hiddenDangers, DeviceHiddenDanger.class);
        relation.setHiddenDangers(deviceHiddenDangers);
        //get multipartfiles
        if (deviceHiddenDangers != null && !deviceHiddenDangers.isEmpty()) {
            MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(request);
            if (DefaultMultipartHttpServletRequest.class.isAssignableFrom(multipartRequest.getClass())) {
                HttpServletRequest otherRequest = ((DefaultMultipartHttpServletRequest) multipartRequest).getRequest();
                if (StandardMultipartHttpServletRequest.class.isAssignableFrom(otherRequest.getClass())) {
                    StandardMultipartHttpServletRequest standardMultipartHttpServletRequest = (StandardMultipartHttpServletRequest) otherRequest;
                    for (int i = 0; i < deviceHiddenDangers.size(); i++) {
                        DeviceHiddenDanger deviceHiddenDanger = deviceHiddenDangers.get(i);
                        deviceHiddenDanger.setFiles(standardMultipartHttpServletRequest.getFiles("files" + i));
                    }
                }
            }
        }
        Integer result = deviceCheckService.saveCheckDeviceRelation(user, relation);
        BusinessCode bc = BusinessCode.valueOf(result);
        msg = MessageBean.create(bc.getCode(), bc.getDescription(), Boolean.class);
        return msg;
    }



    @ApiOperation("新增设备检查隐患信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userCode", value = "当前登录人code,pc端不传，app必传" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "deviceCheckRecordId", value = "设备检查记录Id" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "deviceId", value = "设备Id", required = true, dataType = "String", paramType = "query"),
     })
    @RequestMapping(value = "/saveCheckDanger.htm", method = RequestMethod.POST)
    @Log(title = "新增设备检查隐患信息", businessManipulation = BusinessManipulation.INSERT)
    public MessageBean<?> saveCheckDanger(HttpServletRequest request, @SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(required = false) String userCode,
                                                @RequestParam String deviceCheckRecordId, @RequestParam String deviceId, HiddenDangerDiscovery discovery, String delFileAddress, String keepFileAddress, MultipartFile[] files) {
        MessageBean<?> msg = new MessageBean<>();
        if (null == user) {
            List<StaffBean> staffBeanList = (List<StaffBean>) util.staff(userCode, null).getData();
            if (null != staffBeanList && staffBeanList.size() > 0)
                user = staffBeanList.get(0);
        }
        if (null == user) {
            msg.setCode(BusinessCode.NO_LOGIN.getCode());
            msg.setDescription(BusinessCode.NO_LOGIN.getDescription());
            return msg;
        }
        msg = deviceCheckService.saveCheckDanger(user, deviceCheckRecordId, deviceId, discovery, delFileAddress, keepFileAddress, files);
        return msg;
    }


    @ApiOperation("查询设备的检查结果")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode", value = "公司code" , paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "checkEmployeeCode", value = "设备检查责任人code", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "deviceCheckRecordId", value = "设备检查记录Id" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "searchTag", value = "检查状态" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "当前页", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/queryDeviceResult.htm", method = RequestMethod.POST)
    public MessageBean<DataBean<Device>> queryDeviceResult(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(required = false) String corpCode, @RequestParam String checkEmployeeCode, @RequestParam(required = false) String deviceCheckRecordId,
                                                           @RequestParam(required = false) Integer page, @RequestParam(required = false) Integer pageSize, @RequestParam(required = false) Integer searchTag) {
        MessageBean<DataBean<Device>> msg = new MessageBean<>();
        if (user == null) {
            msg.setCode(BusinessCode.NO_LOGIN.getCode());
            msg.setDescription(BusinessCode.NO_LOGIN.getDescription());
            return msg;
        }

        Integer start = null;
        if (null != page && null != pageSize && page > 0 && pageSize > 0) {
            start = (page <= 1) ? 0 : ((page - 1) * pageSize);
        }
        checkEmployeeCode = checkEmployeeCode.split("_")[0];
        msg.setData(deviceCheckService.fetchDeviceInCheck(corpCode, checkEmployeeCode, deviceCheckRecordId, start, pageSize,searchTag));
        msg.setCode(BusinessCode.SUCCESS.getCode());
        msg.setDescription(BusinessCode.SUCCESS.getDescription());
        return msg;
    }


    @ApiOperation("查询单个设备的检查结果")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode", value = "公司code" , paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "checkEmployeeCode", value = "设备检查责任人code" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "deviceCheckRecordId", value = "设备检查记录Id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "deviceId", value = "设备id", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/queryOneDeviceResult.htm", method = RequestMethod.POST)
    public MessageBean<Device> queryOneDeviceResult(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(required = false) String corpCode, @RequestParam String checkEmployeeCode, @RequestParam(required = false) String deviceCheckRecordId,
                                                           @RequestParam(required = false) String deviceId) {
        MessageBean<Device> msg = new MessageBean<>();
        if (user == null) {
            msg.setCode(BusinessCode.NO_LOGIN.getCode());
            msg.setDescription(BusinessCode.NO_LOGIN.getDescription());
            return msg;
        }
        checkEmployeeCode = checkEmployeeCode.split("_")[0];
        Device device = deviceCheckService.fetchOneDeviceInCheck(corpCode, checkEmployeeCode, deviceCheckRecordId, deviceId);
        msg.setData(device);
        msg.setCode(BusinessCode.SUCCESS.getCode());
        msg.setDescription(BusinessCode.SUCCESS.getDescription());
        return msg;
    }

    @ApiOperation("查询单个设备的隐患记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode", value = "公司code" , paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "deviceCheckRecordId", value = "设备检查记录Id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "deviceId", value = "设备id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "当前页", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/queryOneDeviceOfDanger.htm", method = RequestMethod.POST)
    public MessageBean<?> queryOneDeviceOfDanger(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(required = false) String corpCode, @RequestParam(required = false) String deviceCheckRecordId,
                                                           @RequestParam(required = false) String deviceId,@RequestParam(required = false) Integer page,@RequestParam(required = false) Integer pageSize) {
        MessageBean<List<HiddenDangerDiscovery>> msg = new MessageBean<>();
        if (user == null) {
            msg.setCode(BusinessCode.NO_LOGIN.getCode());
            msg.setDescription(BusinessCode.NO_LOGIN.getDescription());
            return msg;
        }
        msg = deviceCheckService.queryOneDeviceOfDanger(corpCode, deviceCheckRecordId, deviceId,page,pageSize);
        return msg;
    }


    @ApiOperation("上传设备检查的附件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deviceCheckRecordId", value = "设备检查记录Id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "delFileAddress", value = "要删除的照片的地址，多个之间用；分开" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "keepFileAddress", value = "要保留的照片的地址,多个之间用；分开" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "files", value = "附件" , dataType = "MultipartFile", paramType = "query")
    })
    @RequestMapping(value = "/uploadAttachment.htm", method = RequestMethod.POST)
    public MessageBean<Boolean> uploadAttachment(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam String deviceCheckRecordId, @RequestParam(required = false) String delFileAddress,
                                                 @RequestParam(required = false) String keepFileAddress, @RequestParam(required = false) MultipartFile[] files) {
        MessageBean<Boolean> msg = new MessageBean<>();
        if (user == null) {
            msg.setCode(BusinessCode.NO_LOGIN.getCode());
            msg.setDescription(BusinessCode.NO_LOGIN.getDescription());
            return msg;
        }
        msg.setData(deviceCheckService.uploadRecordAttachment(deviceCheckRecordId, delFileAddress, keepFileAddress, files));
        msg.setCode(BusinessCode.SUCCESS.getCode());
        msg.setDescription(BusinessCode.SUCCESS.getDescription());
        return msg;
    }


    @ApiOperation("查询设备检查的附件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deviceCheckRecordId", value = "设备检查记录Id", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/queryAttachment.htm", method = RequestMethod.POST)
    public MessageBean<List<String>> getAttachment(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam String deviceCheckRecordId) {
        MessageBean<List<String>> msg = new MessageBean<>();
        if (user == null) {
            msg.setCode(BusinessCode.NO_LOGIN.getCode());
            msg.setDescription(BusinessCode.NO_LOGIN.getDescription());
            return msg;
        }
        msg.setData(deviceCheckService.getRecordAttachment(deviceCheckRecordId));
        msg.setCode(BusinessCode.SUCCESS.getCode());
        msg.setDescription(BusinessCode.SUCCESS.getDescription());
        return msg;
    }


    @ApiOperation("查询预览报告数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode", value = "公司code" , paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "checkEmployeeCode", value = "设备检查责任人code", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "deviceCheckRecordId", value = "设备检查记录Id", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/preview.htm", method = RequestMethod.POST)
    public MessageBean<Map<String, Object>> preview(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam String corpCode, @RequestParam String checkEmployeeCode, @RequestParam String deviceCheckRecordId) {
        MessageBean<Map<String, Object>> msg = new MessageBean<>();
        if (user == null) {
            msg.setCode(BusinessCode.NO_LOGIN.getCode());
            msg.setDescription(BusinessCode.NO_LOGIN.getDescription());
            return msg;
        }
        Map<String, Object> map = new HashMap<>();
        DeviceCheck deviceCheck = deviceCheckService.fetchOne(deviceCheckRecordId);
        if (deviceCheck == null) {
            msg.setCode(BusinessCode.NO_CHECK_RECORD.getCode());
            msg.setDescription(BusinessCode.NO_CHECK_RECORD.getDescription());
            return msg;
        }
        map.put("deviceCheck", deviceCheck);
        DataBean<Device> deviceDataBean = deviceCheckService.fetchDeviceInCheck(corpCode, deviceCheck.getCheckEmployeeCode().split("_")[0], deviceCheckRecordId, null, null, null);
        if (deviceDataBean != null) {
            List<Device> list = deviceDataBean.getList();
            map.put("devices", list);
        }
        msg.setData(map);
        msg.setCode(BusinessCode.SUCCESS.getCode());
        msg.setDescription(BusinessCode.SUCCESS.getDescription());
        return msg;
    }


    @ApiOperation("设备检查结果")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deviceCheckRecordId", value = "设备检查记录Id", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/submit.htm", method = RequestMethod.POST)
    public MessageBean<Boolean> submit(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam String deviceCheckRecordId) {
        MessageBean<Boolean> msg = new MessageBean<>();
        if (user == null) {
            msg.setCode(BusinessCode.NO_LOGIN.getCode());
            msg.setDescription(BusinessCode.NO_LOGIN.getDescription());
            return msg;
        }
        if (StringUtils.isEmpty(deviceCheckRecordId)) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
            return msg;
        }
        DeviceCheck deviceCheck = deviceCheckService.fetchOne(deviceCheckRecordId);
        if (deviceCheck == null) {
            msg.setCode(BusinessCode.NO_CHECK_RECORD.getCode());
            msg.setDescription(BusinessCode.NO_CHECK_RECORD.getDescription());
            return msg;
        }
        if (deviceCheck.getStatus() != 1) {
            msg.setCode(BusinessCode.CHECK_CANNOT_COMMIT.getCode());
            msg.setDescription(BusinessCode.CHECK_CANNOT_COMMIT.getDescription());
            return msg;
        }
        boolean result = deviceCheckService.submit(user, deviceCheck);
        if (result) {
            return MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Boolean.class);
        }
        return MessageBean.create(BusinessCode.EXCEPTION.getCode(), BusinessCode.EXCEPTION.getDescription(), Boolean.class);
    }


    @ApiOperation("设备检查记录列表导出")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode", value = "公司code" , paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "title", value = "标题" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "checkEmployeeName", value = "检查负责人姓名" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "executerName", value = "检查人姓名" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "状态, 1草稿2提交" , dataType = "int", paramType = "query")})
    @RequestMapping(value = "/exportList.htm", method = RequestMethod.GET)
    public HttpEntity<?> exportList(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(required = false) String corpCode, @RequestParam(required = false) String title, @RequestParam(required = false) String checkEmployeeName,
                                    @RequestParam(required = false) String executerName, @RequestParam(required = false) Integer status) {
        if (null == user) {
            return null;
        }
        Map<String, Object> map = new HashMap<>();
        File file = new File("static/excel/deviceCheckList.xlsx");
        try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream("static/excel/deviceCheckList.xlsx")) {
            List<DeviceCheck> list = deviceCheckService.exportList(corpCode, title, checkEmployeeName, executerName, status);
            map.put("data", list);
            FileUtils.copyInputStreamToFile(inputStream, file);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
        }
        return Excel.createFile("设备检查记录台账", file, "deviceCheckList.btl", map);
    }


}
